package com.auto.survey.activity.monitoring.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.auto.survey.activity.monitoring.entity.MonitoringObject
import com.auto.survey.activity.monitoring.entity.relations.MonitoringWithStationsAndPoints
import kotlinx.coroutines.flow.Flow

/**
 * 监测对象数据访问对象接口
 * 定义与监测对象相关的数据库操作
 */
@Dao
interface MonitoringObjectDao {
    /**
     * 根据项目ID获取监测对象列表
     * @param projectId 项目ID
     * @return 监测对象列表Flow流
     */
    @Query("SELECT * FROM MonitoringObject WHERE projectId = :projectId ORDER BY id DESC")
    fun getMonitoringObjectByProjectId(projectId: Int): Flow<List<MonitoringObject>>

    /**
     * 根据监测对象ID获取监测对象信息
     * @param id 监测对象ID
     * @return 监测对象实体或null
     */
    @Query("SELECT * FROM MonitoringObject WHERE id = :id")
    suspend fun getMonitoringObjectById(id: Int): MonitoringObject?

    /**
     * 插入新监测对象
     * @param monitoring 监测对象实体
     * @return 插入的监测对象ID
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertMonitoringObject(monitoring: MonitoringObject): Long

    /**
     * 更新监测对象信息
     * @param monitoring 监测对象实体
     */
    @Update
    suspend fun updateMonitoringObject(monitoring: MonitoringObject)

    /**
     * 删除监测对象
     * @param monitoring 监测对象实体
     */
    @Delete
    suspend fun deleteMonitoringObject(monitoring: MonitoringObject)

    /**
     * 根据监测对象ID删除监测对象
     * @param id 监测对象ID
     */
    @Query("DELETE FROM MonitoringObject WHERE id = :id")
    suspend fun deleteMonitoringObjectById(id: Int)

    /**
     * 根据项目ID获取监测对象数量
     * @param projectId 项目ID
     * @return 监测对象数量
     */
    @Query("SELECT COUNT(*) FROM MonitoringObject WHERE projectId = :projectId")
    suspend fun getMonitoringObjectCountByProjectId(projectId: Int): Int

    /**
     * 根据监测对象ID获取监测对象及其关联的测站和测点
     * @param monitoringId 监测对象ID
     * @return 监测对象及其关联的测站和测点
     */
    @Transaction
    @Query("SELECT * FROM MonitoringObject WHERE id = :monitoringId")
    suspend fun getMonitoringWithStationsAndPoints(monitoringId: Int): MonitoringWithStationsAndPoints?


}